//
//  OauthLoginViewController.swift
//  Weibo
//
//  Created by mac on 16/1/12.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OauthLoginViewController: UIViewController {

    var webView: UIWebView?
    
    override func loadView() {
        self.webView = UIWebView()
        self.webView?.delegate = self
        
        
        self.view = self.webView
    }
    /**
     client_id	true	string	申请应用时分配的AppKey。
     redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
     */
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        setNav()
        loadWebRequst()
    }

    private func loadWebRequst() {
        let urlString: String = "https://api.weibo.com/oauth2/authorize?client_id=2124965822&redirect_uri=www.itcast.cn"
        let url: NSURL = NSURL(string: urlString)!
        
        guard let urlRequest: NSURLRequest = NSURLRequest(URL: url) else {
            return
        }
        self.webView?.loadRequest(urlRequest)
    }
    
    
    private func initUI() {
        self.webView?.scrollView.bounces = false
    }
    
    private func setNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeNav")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试", style: .Plain, target: self, action: "autoWriteUsesInfo")
        
    }
    
    @objc private func closeNav() {
    
        SVProgressHUD.dismiss()
        
        self.webView?.stopLoading()
        dismissViewControllerAnimated(true, completion: nil)
    }

    @objc private func autoWriteUsesInfo() {
        //执行javascript脚本 填充值
    webView?.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'fmake_one@126.com';document.getElementById('passwd').focus();document.getElementById('passwd').value = 'makemake';")
    }
    
   
    
}


extension OauthLoginViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let _:String = request.URL?.relativeString else {
            return false
        }
        
        if let queryString = request.URL?.query {
            
            let codeStr = "code="
            
            if queryString.containsString(codeStr) {
                
                let code = (queryString as NSString).substringFromIndex(codeStr.characters.count)
                
                loadUserTokenWithCode(code)
                return false
            }
        }
        return true
    }

    
    private func loadUserTokenWithCode(code: String)
    {
        UserCountViewModel().loadUserTokenWithCode(code) { (flag) -> () in
            if flag {
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                     SVProgressHUD.dismiss()
                    NSNotificationCenter.defaultCenter().postNotificationName("setingRootController", object: "Login")
                })
            }
            else {
                SVProgressHUD.showErrorWithStatus("网络连接错误...")
            }
        }
    }
    
}















